package net.takela.common.spring.exception;

import net.takela.common.spring.message.MessageSource;
import net.takela.common.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;


/**
 * @author baboy
 * create at 2023/1/22
 */
public class StatusCodeException extends RuntimeException {
    public static String COMMON_EXCEPTION_REQ_KEY = "common_exception";
    private static final long serialVersionUID = -2008323894680198140L;
    private static final Logger log = LoggerFactory.getLogger(StatusCodeException.class);
    private int code = 0;
    /**
     * @param status status
     */
    public StatusCodeException(int status) {
        this(status, null);
    }
    /**
     * @param status int
     * @param msgKey string
     * @param args vargs
     */
    public StatusCodeException(int status, String msgKey, Object... args) {
        super(MessageSource.getMessage(msgKey != null ? msgKey : "response.status.msg." + status, args));
        String declaringClass = null;
        int lineNumber = 0;
        String methodName = null;

        StackTraceElement tes[] = this.getStackTrace();
        if (tes != null && tes.length > 0) {
            StackTraceElement te = tes[0];
            declaringClass = te.getClassName();
            lineNumber = te.getLineNumber();
            methodName = te.getMethodName();
        }
        String sArgs = "";
        if (args != null && args.length > 0) {
            List l = Arrays.asList(args);
            sArgs = JSONUtils.toString(l);
        }
        log.error("HandleException|class:" + declaringClass + "|method:" + methodName + "|line:" + lineNumber + "|msg:" + msgKey + "|status:" + status + "|args:" + sArgs);
        this.code = status;
    }
    /**
     * @return msg
     */
    public String getErrorMessage() {
        return super.getLocalizedMessage();
    }
    /**
     * @return code
     */
    public int getCode() {
        return code;
    }
    /**
     * @param code int
     */
    public void setCode(int code) {
        this.code = code;
    }

}
